package net.doglog;

import java.util.*;

import javax.jdo.*;

public final class FileUtil {
	
	public static boolean saveFile(File file) {
		boolean result = true;
		PersistenceManager pm = PMF.pm();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.makePersistent(file);
			tx.commit();
		} catch (JDOException e) {
			e.printStackTrace();
			result = false;
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
		return result;
	}

	public static File getFile(String name) {
		File file = null;
		PersistenceManager pm = PMF.pm();
		try {
			file = pm.getObjectById(File.class, File.prefix + name); 
			file = pm.detachCopy(file);
		} catch (JDOObjectNotFoundException e) {
			//file = null;
		} catch (JDOException e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
		return file;
	}

	@SuppressWarnings("unchecked")
	public static List<File> getAllFiles() {
		List<File> files = null;
		PersistenceManager pm = PMF.pm();
		Query query = pm.newQuery(File.class);
		try {
			files = (List<File>) query.execute();
			files = (List<File>) pm.detachCopyAll(files);
		} catch (JDOException e) {
			files = new ArrayList<File>();
		} finally {
			query.closeAll();
			pm.close();
		}
		assert files != null;
		return files;
	}

}
